package com.min.star.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.min.star.model.Teacher;
import com.min.star.service.ITeacherService;
import com.min.star.ui.Json;

@Controller
@RequestMapping("/teacher")
public class TeacherController {

	private Log log = LogFactory.getLog(TeacherController.class);
	
	@Autowired
	private ITeacherService teacherService;
	
	@RequestMapping("/query")
	public String selectTeacherList(Teacher teacher, Model model) {
		List<Teacher> teacherList = this.teacherService.selectTeacherList();
		model.addAttribute("teacherList", teacherList);
		return "/admin/teachers";
	}
	
	@RequestMapping("/info")
	public String info(Model model,HttpServletRequest request) {
		Teacher teacher = (Teacher) request.getSession().getAttribute("teacher");
		Teacher info = this.teacherService.selectById(teacher.getId());
		model.addAttribute("teacher", info);
		System.out.println(info.toString());
		return "/teacher/teacherPersonal";
	}
	
	@RequestMapping("/edit/{data}")
	public String editInfo(@PathVariable("data") List<Object> data, Model model,HttpServletRequest request,HttpSession session) {
		Teacher teacher = (Teacher) request.getSession().getAttribute("teacher");
		System.out.println(teacher.getId());
		int ret = teacherService.editInfo(data.get(0), data.get(1),teacher.getId());
		Teacher info = this.teacherService.selectById(teacher.getId());
		model.addAttribute("teacher", info);
		String  message = null;
		message = ret > 0 ? "保存成功":"保存失败";
		session.setAttribute("message", message);
		return "/teacher/teacherPersonal";
	}
	
	@RequestMapping("/open")
	public String selectTeacherMap(Teacher teacher, Model model) {
		List<Teacher> teacherList = this.teacherService.selectTeacherList();
		model.addAttribute("teacherList", teacherList);
		return "/teacher/teacherList";
	}
	
	@RequestMapping("/list")
	@ResponseBody // 将方法返回值序列化为json
	public Object map(Teacher teacher) {
//		通过page对象设置查询条件,指定分页的页码和页的大小
		Page<Teacher> page = new Page<Teacher>(teacher.getPageNumber(), teacher.getPageSize());
//		通过page条件查询出来的记录存放在另一个page中
		Page<Teacher> pager =this.teacherService.findPage(page,teacher);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("rows", pager.getRecords());
		map.put("total", pager.getTotal());
		System.out.println(map);
		return map;
	}
	
	@RequestMapping("/delete/{ids}")
	@ResponseBody
	public Object delete(@PathVariable("ids") String ids) {
		Json j=new Json();
		int ret=this.teacherService.delete(ids);
		if(ret > 0) {
			j.setMsg("删除成功！");
			j.setCode(0);
		}else {
			j.setMsg("删除失败！");
			j.setCode(-1);
		}
		return j;
	}
	
	@RequestMapping("/add")
	@ResponseBody
	public Object add(@Valid Teacher teacher, BindingResult result) {
		Json j = new Json();
		//服务端验证
		if(result.hasErrors()) {
			return validMessage(result, j);
		}
		//出版社名称重复性检查
		boolean exist = this.teacherService.checkTeacherPhoneExist4Add(teacher);
		if(exist) {
			j.setMsg("教师电话重复，新增失败！");
			j.setCode(-1);
		}else {
			Teacher info = this.teacherService.save(teacher);
			j.setMsg("新增成功！");
			j.setCode(0);
			j.setObj(info);
		}		
		return j;
	}
	
	@RequestMapping("/edit")
	@ResponseBody
	public Object edit(@Valid Teacher teacher, BindingResult result) {
		Json j = new Json();
		//服务端验证
		if(result.hasErrors()) {
			return validMessage(result, j);
		}
		//出版社名称重复性检查
		boolean exist = this.teacherService.checkTeacherPhoneExist4Edit(teacher);
		if(exist) {
			j.setMsg("教师电话重复，修改失败！");
			j.setCode(-1);
		}else {
			Teacher info = this.teacherService.update(teacher);
			j.setMsg("修改成功！");
			j.setCode(0);
			j.setObj(info);
		}		
		return j;
	}
	


	private Object validMessage(BindingResult result, Json j) {
		String msg="";
		List<ObjectError> allErrors = result.getAllErrors();
		if(allErrors!=null && allErrors.size()>0) {
			for(int i=0;i<allErrors.size();i++) {
				ObjectError error = allErrors.get(i);
				if(i == 0) {
					msg += error.getDefaultMessage() + "<br/>";
				}else {
					msg += "<i class='mdi mdi-emoticon-sad'></i>" + error.getDefaultMessage() + "<br/>";
				}
			}
		}
		j.setMsg(msg);
		j.setCode(-1);
		j.setObj(allErrors);
		return j;
	}
	
}
